﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace System
{
    public class BaseHelper
    {
        /// <summary>
        /// 根据泛型实体名称获取对象对应的数据库表名。
        /// </summary>
        /// <typeparam name="T">泛型实体</typeparam>
        /// <returns>泛型实体对应数据库表名</returns>
        public static string GetTableName<T>() where T : new()
        {
            T model = new T();
            return GetTableName(model.GetType());
        }

        /// <summary>
        /// 根据对象类型获取对象对应的数据库表名。
        /// </summary>
        /// <param name="type">实体对象类型</param>
        /// <returns>对应数据库表名</returns>
        public static string GetTableName(MemberInfo type)
        {
            return GetTableName(type.Name);
        }

        /// <summary>
        /// 如果字符为空，则返回字符的默认值。
        /// </summary>
        /// <param name="value">当前字符值</param>
        /// <param name="defaulValue">该字符的默认值</param>
        /// <returns>返回值</returns>
        public static string GetDefaultValue(string value, string defaulValue)
        {
            if (string.IsNullOrEmpty(value))
                value = defaulValue;
            return value;
        }

        /// <summary>
        /// 如果为空，则返回默认值。
        /// </summary>
        /// <param name="value">当前值</param>
        /// <param name="defaulValue">默认值</param>
        /// <returns>返回值</returns>
        public static int? GetDefaultValue(int? value, int? defaulValue)
        {
            if (value == null)
                value = defaulValue;
            return value;
        }

        /// <summary>
        /// 根据对象名返回对应的数据库表名
        /// </summary>
        /// <param name="name">对象名</param>
        /// <returns>返回对应数据库表名</returns>
        public static string GetTableName(string name)
        {
            return name.Substring(0, (name.Length - 4));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model">待处理对象</param>
        /// <returns>结果</returns>
        public static string GetTableName(BaseModel model)
        {
            string name = model.GetType().Name;

            return BaseHelper.GetTableName(name);
        }
    }
}
